<template>
  <div class="app-container">
    <a-form :model="queryParams" ref="queryForm" layout="inline" v-if="showSearch">
      <a-form-item label="流程标识" name="processKey">
        <a-input v-model:value="queryParams.processKey" placeholder="请输入流程标识" allow-clear @pressEnter="handleQuery" />
      </a-form-item>
      <a-form-item label="流程名称" name="processName">
        <a-input v-model:value="queryParams.processName" placeholder="请输入流程名称" allow-clear @pressEnter="handleQuery" />
      </a-form-item>
      <a-form-item label="流程分类" name="category">
        <a-select v-model:value="queryParams.category" allowClear placeholder="请选择" style="width: 200px">
          <a-select-option v-for="item in categoryOptions" :key="item.categoryId" :value="item.code">
            {{ item.categoryName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" @click="handleQuery">
            <template #icon><SearchOutlined /></template>
            搜索
          </a-button>
          <a-button @click="resetQuery">
            <template #icon><ReloadOutlined /></template>
            重置
          </a-button>
        </a-space>
      </a-form-item>
    </a-form>

    <div class="table-operations" style="margin-bottom: 16px">
      <a-row :gutter="16">
        <a-col>
          <a-button type="warning" v-hasPermi="['workflow:process:startExport']" @click="handleExport">
            <template #icon><DownloadOutlined /></template>
            导出
          </a-button>
        </a-col>
        <a-col flex="auto">
          <div style="float: right">
            <right-toolbar :show-search.sync="showSearch" @query-table="getList"></right-toolbar>
          </div>
        </a-col>
      </a-row>
    </div>

    <a-table :loading="loading" :columns="columns" :data-source="processList" :pagination="false">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'index'">
          {{ record.index + 1 }}
        </template>
        <template v-else-if="column.key === 'processName'">
          <a @click="handleProcessView(record)">{{ record.processName }}</a>
        </template>
        <template v-else-if="column.key === 'version'">
          <a-tag>v{{ record.version }}</a-tag>
        </template>
        <template v-else-if="column.key === 'status'">
          <a-tag :color="!record.suspended ? 'success' : 'warning'">
            {{ !record.suspended ? '激活' : '挂起' }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-button type="link" v-hasPermi="['workflow:process:start']" @click="handleStart(record)">
            <template #icon><PlayCircleOutlined /></template>
            发起
          </a-button>
        </template>
      </template>
    </a-table>

    <a-pagination
      v-if="total > 0"
      v-model:current="queryParams.pageNum"
      v-model:pageSize="queryParams.pageSize"
      :total="total"
      @change="getList"
      show-size-changer
      show-quick-jumper
    />

    <a-modal :title="processView.title" v-model:open="processView.open" width="70%" :footer="null">
      <process-viewer :key="`designer-${processView.index}`" :xml="processView.xmlData" :style="{ height: '400px' }" />
    </a-modal>
  </div>
</template>

<script setup name="WorkProcess">
  import { processApi } from '/@/api/workflow/work';
  import { categoryApi } from '/@/api/workflow/category';
  import ProcessViewer from '@/components/ProcessViewer';

  const router = useRouter();
  const columns = [
    {
      title: '序号',
      key: 'index',
      width: 50,
    },
    {
      title: '流程标识',
      dataIndex: 'processKey',
      key: 'processKey',
      ellipsis: true,
    },
    {
      title: '流程名称',
      key: 'processName',
      ellipsis: true,
    },
    {
      title: '流程分类',
      dataIndex: 'categoryName',
      key: 'category',
      customRender: ({ record }) => categoryFormat(record),
    },
    {
      title: '流程版本',
      key: 'version',
    },
    {
      title: '状态',
      key: 'status',
    },
    {
      title: '部署时间',
      dataIndex: 'deploymentTime',
      key: 'deploymentTime',
      width: 180,
    },
    {
      title: '操作',
      key: 'action',
    },
  ];

  const loading = ref(true);
  const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    processKey: undefined,
    processName: undefined,
    category: undefined,
  });
  const showSearch = ref(true);
  const total = ref(0);
  const categoryOptions = ref([]);
  const categoryProps = ref({
    label: 'categoryName',
    value: 'code',
  });
  const processList = ref([]);
  const processView = reactive({
    title: '',
    open: false,
    index: undefined,
    xmlData: '',
  });

  onMounted(() => {
    getCategoryList();
    getList();
  });

  const getCategoryList = async () => {
    categoryApi.listAllCategory().then((response) => (categoryOptions.value = response.data));
  };

  const getList = async () => {
    loading.value = true;
    processApi.listProcess(queryParams.value).then((response) => {
      processList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  };

  const handleQuery = async () => {
    queryParams.value.pageNum = 1;
    getList();
  };

  const resetQuery = async () => {
    queryForm.value.resetFields();
    handleQuery();
  };

  const handleProcessView = async (row) => {
    let definitionId = row.definitionId;
    processView.title = '流程图';
    processView.index = definitionId;
    // 发送请求，获取xml
    processApi.getBpmnXml(definitionId).then((res) => {
      processView.xmlData = res.data;
    });
    processView.open = true;
  };

  const handleStart = async (row) => {
    router.push({
      path: '/workflow/process/start/' + row.deploymentId,
      query: {
        definitionId: row.definitionId,
      },
    });
  };
  /** 导出按钮操作 */
  const handleExport = async () => {
    proxy?.download(
      'workflow/process/startExport',
      {
        ...queryParams.value,
      },
      `wf_start_process_${new Date().getTime()}.xlsx`
    );
  };
  const categoryFormat = (row, column) => {
    return categoryOptions.value.find((k) => k.code === row.category)?.categoryName ?? '';
  };
</script>

<style scoped>
  .table-operations {
    margin-bottom: 16px;
  }
</style>
